#include <iostream>
#include <fstream>
#include <stdio.h>
#include <vector>
#include <regex>
#include <iterator>
#include <algorithm>
// #include <string>
#include <sys/statfs.h>
#include <unistd.h>

int isExistDir(const char* dir)
{
    if(access(dir, 0) == -1)
        return -1;
    return 0;
}

int utilGetMemoryUsage()
{
    FILE *fd;
    int memory_usage = 0;
    char buff[256] = "";
    char info_name[20] = "";
    uint32_t memory_tatol,memory_free,memory_avail;
    /*read memory info*/
    fd = fopen("/proc/meminfo", "r");
    fgets(buff, sizeof(buff), fd);
    sscanf(buff, "%s %lu ", info_name, &memory_tatol);
    fgets(buff, sizeof(buff), fd);
    sscanf(buff, "%s %lu ", info_name, &memory_free);
    fgets(buff, sizeof(buff), fd);
    sscanf(buff, "%s %lu ", info_name, &memory_avail);
    fclose(fd); 
    memory_usage = (int)((1-memory_avail*1.0/memory_tatol*1.0)*100.0);
    return memory_usage;
}

int GetDiskUsage()
{
    int disk_have = 0;
    struct statfs sfs;
    int ret = 100;
    #ifdef __x86_64__
        ret = statfs("/", &sfs);
        printf("x86\n");
    #endif

    #ifdef __aarch64__
    if(0 == isExistDir("/dev/mmcblk1p1"))
        ret = statfs("/dev/mmcblk1p1", &sfs);
    else
        ret = 100;
    printf("arm\n");
    #endif
    
    disk_have = (sfs.f_blocks - sfs.f_bfree ) * 100 / (sfs.f_blocks - sfs.f_bfree + sfs.f_bavail) + 1;
    printf("disk_have : %d\n",disk_have);
    return 0;
}

int utilGetCpuUsage()
{
    FILE *fp;
    int cup_usage = 0;

    if (0 != system("vmstat > info.txt"))
        return cup_usage;
    std::ifstream File("info.txt");
    if (!File)
    {
        return cup_usage;
    }
    std::string line, last_line;
    while (std::getline(File, line))
    {
        last_line = line;
    }
    File.close();

    std::istringstream str(last_line);
    std::string out;
    std::vector<int> sysinfo;
    while (str >> out)
    {
        sysinfo.push_back(std::atoi(out.c_str()));
    }
    if (sysinfo.size() == 17)
    {
        cup_usage = 100 - sysinfo[14];
    }
    return cup_usage;
}

int main(int argv, char**argc)
{
    printf("************  test hello zc!!!   **************\n");
    /* add test code! */
    // std::string cpu_stat_string;
    // std::ifstream cpu_stat("/proc/stat");
    // std::getline(cpu_stat, cpu_stat_string);

    // std::cout << cpu_stat_string << std::endl;
    // std::regex ws("\\s+");


    // std::vector<std::string> cpu_stat_vec(std::sregex_token_iterator(cpu_stat_string.begin(), cpu_stat_string.end(), ws, -1),  
    // std::sregex_token_iterator());
    // for(auto &str:cpu_stat_vec){
    //     std::cout << str << std::endl;
    // }

    // int cpu_time2 = std::stoi(cpu_stat_vec[1]) + std::stoi(cpu_stat_vec[2])
    //         + std::stoi(cpu_stat_vec[3]) + std::stoi(cpu_stat_vec[4]);
    // std::cout << cpu_time2 << std::endl;       
    int usage = GetDiskUsage();
    printf("usage: %d\n",usage);
    return 0;
}
